package org.chen.flight.util;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.flight.FlightSearchData;
import org.chen.common.flight.FlightSegment;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.List;

// SignUtils.java - 签名工具类
@Component
@Slf4j
public class SignUtils {
    
    /**
     * 生成携程API签名
     */
    public static String generateCtripSign(FlightSearchData searchData) {
        StringBuilder signData = new StringBuilder();
        signData.append(searchData.getTransactionID());
        
        // 根据行程类型构造签名字符串
        List<FlightSegment> segments = searchData.getFlightSegments();
        
        if ("S".equals(searchData.getFlightWay())) {
            log.info("单程：{}", searchData.getFlightWay());
            // 单程: transactionid + departureCityCode + arrivalCityCode + departureDate
            FlightSegment segment = segments.get(0);
            signData.append(segment.getDepartureCityCode())
                   .append(segment.getArrivalCityCode())
                   .append(segment.getDepartureDate());
        } else if ("D".equals(searchData.getFlightWay())) {
            log.info("往返{}", searchData.getFlightWay());
            // 往返: transactionid + departureCityCode + arrivalCityCode + departureDate + departureCityCode + arrivalCityCode + departureDate
            for (FlightSegment segment : segments) {
                signData.append(segment.getDepartureCityCode())
                       .append(segment.getArrivalCityCode())
                       .append(segment.getDepartureDate());
            }
        }
        
        // MD5加密
        String signString = signData.toString();
        String md5Sign = DigestUtils.md5DigestAsHex(signString.getBytes());
        
        log.debug("生成签名 - 原始字符串: {}, MD5: {}", signString, md5Sign);
        return md5Sign;
    }
}